package com.zh.mediaservice.service.impl;

import com.zh.mediacommon.util.MessageHandleUtil;
import com.zh.mediapojo.entity.Message;
import com.zh.mediaservice.mapper.MessageMapper;
import com.zh.mediaservice.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.websocket.Session;
import java.util.List;

@Slf4j
@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public void save(Message message1, boolean isUser) {
        messageMapper.save(message1,isUser);
    }

    @Override
    public void saveToRedisWithUnreadMessages(Message message1, boolean isUser) {
        Long id = message1.getReceiver();
        String key="";
        if (isUser)
            key = "医生"+id;
        else
            key = "用户"+id;
        String message = MessageHandleUtil.getMessage(message1);
        redisTemplate.opsForList().leftPush(key,message);
    }

    @Override
    public boolean sendToUnreadMessages(String key, Session session) {
        ListOperations listOperations = redisTemplate.opsForList();
        try{
            log.info("这次的key为{}", key);
            List<String> messageList =  listOperations.range(key, 0, -1);
            log.info("获取未发送消息{}", messageList);
            if(messageList==null || messageList.isEmpty())
                return false;
            for (String message : messageList) {
                session.getAsyncRemote().sendText(message);
                //防止消息过多出现服务器异常
                Thread.sleep(200);
            }
            boolean isUser=key.contains("医生");
            List<Message> messageList1 = MessageHandleUtil.getMessageList(messageList);
            messageMapper.saveMessageList(messageList1, isUser);
            listOperations.trim(key,messageList.size(),-1);
            return true;
        }catch (Exception e){
            log.error("there"+e.getMessage());
            return false;
        }

    }
}
